<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/22
 * Time: 11:34
 */

namespace app\common\model;
use think\Db;
use think\Loader;

class Order
{
    protected $order=[];
    protected $table='';
    public function getOrder($myOrderId){
        return $this->_find_my_order($myOrderId);
    }

    /**
     * @param $data
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function makeOrder($data){
        if(empty($data['cp_order_id'])||empty($data['game_id'])){
            return err('参数不全:缺少游戏ID或游戏单号');
        }
        $order=$this->_find_cp_order($data['cp_order_id'],$data['game_id']);
        if($order) {
            return err('单号已存在,请返回重新选择物品');
            if($data['pay_type']===$order['pay_type']){
                return suc('',$order);
            }else{
                return err('支付方式不一致,请重新下单');
            }

        }
        if(empty($data['my_user_id'])||empty($data['channel_id'])){
            return err('用户id或渠道id不能为空');
        }

        $data['my_order_id']=$this->makeOrderId($data['my_user_id'],$data['channel_id']);

        //Log::record('orderdata:'.json_encode($data));
        $rs=$this->_insert($data);
        if($rs){
            return suc('',$data);
        }else{
            return err('订单创建失败');
        }



    }
    public function findCpOrder($cpOrderId,$gameId){
        return $this->_find_cp_order($cpOrderId,$gameId);
    }

    public function updateOrder($data){
        return $this->_update($data);
    }
    public function getMyOrder($myOrderId)
    {
        $order = $this->_find_my_order($myOrderId);
        if ($order) {
            return $order;
        } else {
            return [];
        }
    }
    public function makeOrderId($myUserId,$channelId){
        $redis=new Redis();
        $time=date('ymdHis',time());
        $key='common:orderId:'.$time;
        $id=$redis->incr($key);
        $id=str_pad($id,4,0,STR_PAD_LEFT);
        $redis->expire($key,30);
        if($this->isDebug($myUserId,$channelId)){
            $orderId='MYtest'.$time.$id;
        }else{
            $orderId='MY'.$time.$id;
        }
        return $orderId;
    }
    public function isDebug($myUserId,$channelId=1000){
        if(!empty($myUserId)){
            $key='common:debug:'.$myUserId;
        }else{
            return 0;
        }
        $redis=new Redis();
        $debug=$redis->get($key);
        if($debug){
            return 1;
        }else{
            return 0;
        }

    }

    /**
     * @param $myOrderId
     * @param $chOrderId
     * @param $payTime
     * @param $chUserName
     * @param $totalPrice
     * @param $payOrderId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function paySuccess($myOrderId,$chOrderId,$payTime,$chUserName,$totalPrice,$payOrderId){
        $table=get_order_table($myOrderId);
        $data=[
            'ch_order_id'=>$chOrderId,
            'pay_order_id'=>$payOrderId,
            'ch_user_name'=>$chUserName,
            'pay_result'=>1,
            'pay_time'=>$payTime
        ];
        $order=Db::name($table)
            ->where(['my_order_id'=>$myOrderId])
            ->find();
        if(empty($order)){
            Log::record('pay_notify:没有找到该订单'.$myOrderId,'error','error');
            return err('pay_notify:没有找到该订单');
        }else{
            if($order['total_price']-$totalPrice!=0){
                Log::record('pay_notify:金额不匹配'.$myOrderId,'error','error');
                return err('pay_notify:金额不匹配');
            }
            if(!empty($order['pay_order_id'])&&$order['pay_order_id']!=$payOrderId){
                return err('pay_notify:渠道单号不匹配');
            }
            if($order['pay_result']!=1){
                try{
                    Db::name($table)
                        ->where(['my_order_id'=>$myOrderId])
                        ->update($data);
                    return suc('pay_notify:成功');
                }catch(\Exception $e){
                    return err('pay_notify:'.$e->getMessage());
                }
            }else{
                return suc('pay_notify:已处理直接返回');
            }
        }


    }

    /**
     * 获取用户的所有订单
     * @param $myUserId
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getOrdersByUid($myUserId){
        $db=Db::connect();
        $tables=$db->getTables(config('database.database'));
        $prefix=config('database.prefix');
        krsort($tables);
        $orders=[];
        foreach($tables as $v){
            if(match($v,"/^{$prefix}pay_order_y_20[0-9][0-9]$/")){
                $order=$db->table($v)
                    ->where(['my_user_id'=>$myUserId])
                    ->select();
                $orders=array_merge($orders,$order);
            }
        }
        return $orders;
    }

    public function getOrderByCpOrderId($cpOrderId,$gameId){
        return $this->_find_cp_order($cpOrderId,$gameId);

    }

    /**
     * 插入订单数据,如果表不存在就先创建表
     * @param $data
     * @return bool|int|string
     * @throws \think\Exception
     */
    private function _insert($data){
        if(!isset($data['order_time'])){
            $data['order_time']=time();
        }
        $year=date('Y',$data['order_time']);
        $db=Db::connect();
        $tables=$db->getTables(config('database.database'));
        $prefix=config('database.prefix');
        krsort($tables);
        $tableExists=false;
        foreach($tables as $v){
            if($v==$prefix.'pay_order_y_'.$year){
                $this->table='pay_order_y_'.$year;
                $tableExists=true;
                break;
            }
        }
        //如果表不存在就创建
        if(!$tableExists){
            $sql = "CREATE TABLE `{$prefix}pay_order_y_{$year}` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `device_id` varchar(64) CHARACTER SET utf8 DEFAULT '' COMMENT '设备id',
  `game_id` int(11) unsigned DEFAULT '0' COMMENT '游戏id',
  `channel_id` int(11) DEFAULT '0' COMMENT '渠道',
  `cps_id` int(11) DEFAULT NULL,
  `reg_cps_id` int(11) DEFAULT NULL,
  `my_user_id` varchar(64) CHARACTER SET utf8 DEFAULT '0' COMMENT '融合用户id',
  `my_user_name` varchar(64) CHARACTER SET utf8 DEFAULT NULL,
  `ch_user_id` varchar(64) CHARACTER SET utf8 DEFAULT '' COMMENT '渠道用户id',
  `cp_order_id` varchar(64) CHARACTER SET utf8 DEFAULT '' COMMENT '游戏方订单id',
  `ch_order_id` varchar(64) CHARACTER SET utf8 DEFAULT '' COMMENT '渠道方订单id',
  `my_order_id` varchar(64) CHARACTER SET utf8 DEFAULT '' COMMENT '融合sdk订单id',
  `product_id` varchar(64) CHARACTER SET utf8 DEFAULT '0' COMMENT '产品id',
  `product_name` varchar(255) CHARACTER SET utf8 DEFAULT '' COMMENT '产品名称',
  `product_unit` varchar(64) CHARACTER SET utf8 DEFAULT '' COMMENT '产品单位',
  `product_des` varchar(255) CHARACTER SET utf8 DEFAULT '' COMMENT '产品详情',
  `buy_quantity` int(11) unsigned DEFAULT '0' COMMENT '购买数量',
  `product_price` int(11) unsigned DEFAULT '0' COMMENT '产品金额分',
  `total_price` int(11) unsigned DEFAULT '0' COMMENT '订单总金额分',
  `coin` int(11) unsigned DEFAULT '0' COMMENT '游戏币值',
  `user_info` varchar(500) CHARACTER SET utf8 DEFAULT '' COMMENT '订单自定义信息',
  `ext` varchar(2000) CHARACTER SET utf8 DEFAULT '' COMMENT '扩展参数',
  `pay_type` varchar(32) CHARACTER SET utf8 DEFAULT NULL COMMENT '支付类型 alipay,wxpay,mili',
  `role_id` varchar(64) CHARACTER SET utf8 DEFAULT '' COMMENT '角色id',
  `role_name` varchar(64) CHARACTER SET utf8 DEFAULT '' COMMENT '角色名',
  `level` int(11) unsigned DEFAULT '0' COMMENT '角色等级',
  `party_name` varchar(64) CHARACTER SET utf8 DEFAULT '' COMMENT '角色所在公会名',
  `vip` varchar(32) CHARACTER SET utf8 DEFAULT '' COMMENT 'vip级别',
  `server_id` varchar(64) CHARACTER SET utf8 DEFAULT '0' COMMENT '服务器id',
  `server_name` varchar(64) CHARACTER SET utf8 DEFAULT '0' COMMENT '服务器名称',
  `ip` char(15) CHARACTER SET utf8 DEFAULT '' COMMENT 'ip地址',
  `order_time` int(11) unsigned DEFAULT '0' COMMENT '订单生成时间',
  `pay_order_id` varchar(64) CHARACTER SET utf8 DEFAULT NULL COMMENT '支付单号',
  `pay_time` int(11) unsigned DEFAULT '0' COMMENT '订单支付时间',
  `pay_result` tinyint(1) unsigned DEFAULT '0' COMMENT '支付结果：0未支付，1已支付',
  `game_time` int(11) DEFAULT NULL,
  `game_result` tinyint(1) unsigned DEFAULT '0' COMMENT '游戏到帐：0未到帐，1已到帐',
  `rebate_time` int(11) DEFAULT '0' COMMENT '返利操作时间',
  `device_type` varchar(20) CHARACTER SET utf8 DEFAULT '' COMMENT '设备类型（AND_SDK，IOS_SDK，AND_WAP，IOS_WAP）',
  `debug` tinyint(1) DEFAULT '0' COMMENT '是否为测试数据',
  `is_show` tinyint(4) DEFAULT NULL,
  `ratio` int(11) DEFAULT NULL,
  `ch_user_name` varchar(64) CHARACTER SET utf8 DEFAULT NULL,
  `notifyed` tinyint(4) DEFAULT '0' COMMENT '是否有过通知',
  `game_notify_failed` tinyint(4) DEFAULT '0' COMMENT '游戏通知失败次数',
  `bundle_id` varchar(30) COLLATE utf8mb4_unicode_ci DEFAULT '' COMMENT 'ios的包名',
  `client_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `my_order_id` (`my_order_id`) USING BTREE,
  KEY `cp` (`game_id`,`cp_order_id`) USING BTREE,
  KEY `game_id` (`game_id`) USING BTREE,
  KEY `pay_result` (`pay_result`) USING BTREE,
  KEY `game_result` (`game_result`) USING BTREE,
  KEY `debug` (`debug`) USING BTREE,
  KEY `reg_cps_id` (`reg_cps_id`) USING BTREE,
  KEY `my_user_id` (`my_user_id`) USING BTREE,
  KEY `my_user_name` (`my_user_name`) USING BTREE,
  KEY `cp_order_id` (`cp_order_id`) USING BTREE,
  KEY `ch_order_id` (`ch_order_id`) USING BTREE,
  KEY `order_time` (`order_time`) USING BTREE,
  KEY `pay_time` (`pay_time`) USING BTREE,
  KEY `data_inx` (`channel_id`,`pay_time`,`debug`,`pay_result`)
) ENGINE=InnoDB AUTO_INCREMENT=150977 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='支付订单表';";

            try{
                Db::execute($sql);//创建表
            }catch(\Exception $e){
                //Log::record('create order table error.'.$e->getMessage());
            }
        }
        $input=Loader::model('\\app\\common\\model\\Input');
        $insertData=[
            'game_id'=>get_array_value($data,'game_id',0),
            'channel_id'=>get_array_value($data,'channel_id',0),
            'cps_id'=>get_array_value($data,'cps_id',0),
            'reg_cps_id'=>get_array_value($data,'reg_cps_id',0),
            'my_user_id'=>get_array_value($data,'my_user_id',''),
            'my_user_name'=>get_array_value($data,'my_user_name',''),
            'ch_user_id'=>get_array_value($data,'ch_user_id',''),
            'cp_order_id'=>get_array_value($data,'cp_order_id',''),
            'my_order_id'=>get_array_value($data,'my_order_id',''),
            'ch_order_id'=>get_array_value($data,'ch_order_id',''),
            'product_id'=>get_array_value($data,'product_id',''),
            'product_name'=>get_array_value($data,'product_name',''),
            'product_unit'=>get_array_value($data,'product_unit',''),
            'product_des'=>get_array_value($data,'product_des',''),
            'buy_quantity'=>get_array_value($data,'buy_quantity',0),
            'product_price'=>get_array_value($data,'product_price',0),
            'total_price'=>get_array_value($data,'total_price',0),
            'ratio'=>get_array_value($data,'ratio',0),
            'coin'=>get_array_value($data,'coin',0),
            'ext'=>get_array_value($data,'ext',''),
            'pay_type'=>get_array_value($data,'pay_type',''),
            'role_id'=>get_array_value($data,'role_id',''),
            'role_name'=>get_array_value($data,'role_name',''),
            'level'=>get_array_value($data,'level',0),
            'party_name'=>get_array_value($data,'party_name',''),
            'vip'=>get_array_value($data,'vip',''),
            'server_id'=>get_array_value($data,'server_id',''),
            'server_name'=>get_array_value($data,'server_name',''),
            'ip'=>get_array_value($data,'ip',request()->ip()),
            'order_time'=>get_array_value($data,'order_time',time()),
            'pay_order_id'=>get_array_value($data,'pay_order_id',''),
            'pay_time'=>get_array_value($data,'pay_time',0),
            'pay_result'=>get_array_value($data,'pay_result',0),
            'game_time'=>get_array_value($data,'game_time',0),
            'game_result'=>get_array_value($data,'game_result',0),
            'rebate_time'=>get_array_value($data,'rebate_time',0),
            'device_type'=>get_array_value($data,'device_type',''),
            'debug'=>get_array_value($data,'debug',0),
            'is_show'=>get_array_value($data,'is_show',1),
            'user_info'=>get_array_value($data,'user_info',''),
            'client_id'=>$input->getClientId()

        ];
        try{
            return Db::name('pay_order_y_'.$year)->insert($insertData);
        }catch(\Exception $e){
            return false;
        }

    }

    /**
     * @param $myOrderId
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function _find_my_order($myOrderId){
        if(empty($myOrderId)){
            return [];
        }
        $table=get_order_table($myOrderId);
        $order=Db::name($table)
            ->where(['my_order_id'=>$myOrderId])
            ->find();
        return $order;
    }

    /**
     * @param $cpOrderId
     * @param $gameId
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function _find_cp_order($cpOrderId,$gameId){
        if(empty($cpOrderId)||empty($gameId)){
            return [];
        }
        $db=Db::connect();
        $tables=$db->getTables(config('database.database'));
        $prefix=config('database.prefix');
        $order=[];
        krsort($tables);
        foreach($tables as $v){
            if(match($v,"/^{$prefix}pay_order_y_20[0-9][0-9]$/")){
                $order=$db->table($v)
                    ->where(['cp_order_id'=>$cpOrderId,'game_id'=>$gameId])
                    ->find();
                if($order){
                    $this->table=substr($v,4);
                    $this->order=$order;
                    break;
                }

            }
        }
        return $order;
    }

    /**
     * @param $data
     * @return bool
     */
    private function _update($data){
        if(!isset($data['my_order_id'])){
            return false;
        }
        $table=get_order_table($data['my_order_id']);
        $myOrderId=$data['my_order_id'];
        unset($data['my_order_id']);
        try{
            Db::name($table)->where(['my_order_id'=>$myOrderId])->update($data);
            return true;
        }catch(\Exception $e){
            Log::record('order update error.'.$e->getMessage()."|data:".json_encode($data));
            return false;
        }
    }

}